package cn.edu.ncut.cs.springboot.springsecuritydemo.controller;

import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.User;
import cn.edu.ncut.cs.springboot.springsecuritydemo.service.UserService;
import cn.edu.ncut.cs.springboot.springsecuritydemo.vo.JsonResult;
import cn.edu.ncut.cs.springboot.springsecuritydemo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/usercreate")
public class UserRestController {

    @Autowired
    private UserService userService;

    @GetMapping("/view/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public JsonResult getUserInfo(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setPassword(user.getPassword());
        userVO.setTimestamp(user.getGmtModified().toEpochMilli());
        return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "获取数据成功！", userVO);
    }

    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN')")
    public JsonResult getUserList() {
        try {
            List<UserVO> userList = userService.findAll();
            return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "获取数据成功！", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(JsonResult.JsonResultCode.ERROR, "获取数据失败！", null);
        }
    }

    @PostMapping("/create")
    @PreAuthorize("hasRole('ADMIN')")
    public JsonResult createUser(@RequestBody UserVO userVO) {
        boolean success = userService.create(userVO);
        if (success) {
            return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "用户创建成功！", userVO);
        } else {
            return new JsonResult(JsonResult.JsonResultCode.ERROR, "用户创建失败！", null);
        }
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public JsonResult updateUser(@PathVariable Long id, @RequestBody UserVO userVO) {
        User updatedUser = userService.updateUser(id, userVO);
        if (updatedUser != null) {
            return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "用户更新成功！", updatedUser);
        } else {
            return new JsonResult(JsonResult.JsonResultCode.ERROR, "用户更新失败！", null);
        }
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public JsonResult deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "用户删除成功！", null);
    }

}
